package xianhenyuan.csv.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import xianhenyuan.csv.entity.DemoEntity;
import xianhenyuan.csv.service.demoService;
import xianhenyuan.csv.utils.ToolUtil;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
public class demoController {


    @Autowired
    private demoService demoService;

    @RequestMapping("/")
    public List<DemoEntity> test(){
        return demoService.findAll();
    }


    @RequestMapping("/download")
    public void download(HttpServletResponse response) throws Exception{
        //设置 header
        String fileName = ToolUtil.getStringTodayMillisecond()+".csv";
        response.setHeader("Content-type", "text/csv; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\";charset=utf-8");

        //数据
        List<DemoEntity> demos = demoService.findAll();

        //表头
        String[] header = {"字段一", "字段二", "字段三", "字段四", "字段五"};
        //字段名
        String[] field = {"one", "two", "three", "four", "five"};
        ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
                CsvPreference.STANDARD_PREFERENCE);

        csvWriter.writeHeader(header);

        for (DemoEntity demo : demos) {
            csvWriter.write(demo,field);
        }

        csvWriter.close();
    }

}
